package com.ruoyi.app.common.jwt;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.app.User;
import com.ruoyi.system.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserMapper userService;
    @Autowired
    RedisCache redisCache;


    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException
    {
        String[] strings = phone.split(":");
        User user = userService.selectUserByUserPhone(strings[0],strings[1]);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", phone);
            throw new UsernameNotFoundException("登录用户：" + phone + " 不存在");
        }

        else if (UserStatus.DISABLE.getCode().equals(user.getState()))
        {
            log.info("登录用户：{} 已被停用.", phone);
            throw new UsernameNotFoundException("对不起，您的账号：" + phone + " 已停用");
        }
        redisCache.deleteObject(phone);
        return user;
    }


}
